package com.pilipili.serverapi.controller.manageUser;

import com.pilipili.common.Exception.BusinessRuntimeException;
import com.pilipili.common.controller.AbstractController;
import com.pilipili.common.controller.PageCommResult;
import com.pilipili.common.util.BeanUtils;
import com.pilipili.serverapi.ErrorCode;
import com.pilipili.serverapi.config.ShiroConfig;
import com.pilipili.serverapi.manageUser.dto.req.PermissionDto;
import com.pilipili.serverapi.manageUser.dto.req.PermissionWithIdDto;
import com.pilipili.serverapi.manageUser.dto.resp.PermissionWithCreateTimeDto;
import com.pilipili.serverapi.manageUser.entity.Permission;
import com.pilipili.serverapi.manageUser.service.PermissionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 权限管理接口
 *
 * @author chen.guosheng
 */
@Api(description = "权限管理接口")
@RestController
@RequestMapping("/serverapi/permission")
public class PermissionController extends AbstractController {

    private static final Logger LOG = LoggerFactory.getLogger(ManageUserController.class);

    @Autowired
    private PermissionService permissionService;

    @ApiOperation(value = "新增权限")
    @ApiImplicitParam(name="Token", value="用于验证登录的token", paramType="header",dataType="string")
    @RequiresPermissions("permissionManage")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public PageCommResult<Object> add(@Valid @RequestBody PermissionDto permissionDto, BindingResult bindingResult) {
        LOG.info(" access /serverapi/permission/add permissionDto {} ", permissionDto);
        if (bindingResult.hasErrors()) {
            throw new BusinessRuntimeException(ErrorCode.PRAMERROR.getCode(),
                    bindingResult.getFieldError().getDefaultMessage());
        }
        if(permissionService.exits("permissionName", permissionDto.getPermissionName(), Permission.class)){
            throw new BusinessRuntimeException(ErrorCode.PERMISSION_EXIST);
        }
        Permission permission = new Permission();
        BeanUtils.copyProperties(permissionDto, permission);
        permission.setParentId(0L);
        permissionService.save(permission);
        ShiroConfig.clearCache();
        return this.successPageResultWithEmptyResult();
    }

    @ApiOperation(value = "编辑权限")
    @ApiImplicitParam(name="Token", value="用于验证登录的token", paramType="header",dataType="string")
    @RequiresPermissions("permissionManage")
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public PageCommResult<Object> edit(@Valid @RequestBody PermissionWithIdDto permissionWithIdDto,
                                       BindingResult bindingResult) {
        LOG.info(" access /serverapi/permission/edit permissionWithIdDto {} ", permissionWithIdDto);
        if (bindingResult.hasErrors()) {
            throw new BusinessRuntimeException(ErrorCode.PRAMERROR.getCode(),
                    bindingResult.getFieldError().getDefaultMessage());
        }
        permissionService.editAfterFind(permissionWithIdDto.getId(), permissionWithIdDto, ErrorCode.PERMISSION_NOT_FOUND);
        ShiroConfig.clearCache();
        return this.successPageResultWithEmptyResult();
    }

    @ApiOperation(value = "搜索权限")
    @ApiImplicitParam(name="Token", value="用于验证登录的token", paramType="header",dataType="string")
    @RequiresPermissions("permissionManage")
    @RequestMapping(value = "/search", method = RequestMethod.GET)
    public PageCommResult<PermissionWithCreateTimeDto> search(@RequestParam(value = "permissionName", defaultValue = "") String permissionName,
                                                              @RequestParam(value = "currentPage", defaultValue = "0") Integer currentPage,
                                                              @RequestParam(value = "pageCount", defaultValue = "10") Integer pageCount) {
        LOG.info(" access /serverapi/role/search roleName {} start {} count {} ", permissionName, currentPage, pageCount);
        return permissionService.search(permissionName, currentPage, pageCount);
    }

    @ApiOperation(value = "批量删除权限")
    @ApiImplicitParam(name="Token", value="用于验证登录的token", paramType="header",dataType="string")
    @RequiresPermissions("permissionManage")
    @RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
    public PageCommResult<Object> batchDelete(@RequestParam("permissionIds") List<Long> permissionIds) {
        LOG.info(" access /serverapi/permission/batchDelete permissionIds {} ", permissionIds);
        permissionService.batchDelete(permissionIds);
        ShiroConfig.clearCache();
        return this.successPageResultWithEmptyResult();
    }

    @ApiOperation(value = "验证权限管理权限")
    @ApiImplicitParam(name="Token", value="用于验证登录的token", paramType="header",dataType="string")
    @RequiresPermissions("permissionManage")
    @RequestMapping(value = "/testAuth", method = RequestMethod.POST)
    public PageCommResult<Object> testAuth() {
        LOG.info(" access /serverapi/permission/testAuth");
        return this.successPageResultWithEmptyResult();
    }
}
